import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

import { LoveRecycManageService } from '../love-recyc-manage.service';

@Component({
  selector: 'app-love-modselect-add',
  templateUrl: './love-modselect-add.component.html',
  styleUrls: ['./love-modselect-add.component.scss']
})
export class LoveModselectAddComponent implements OnInit {

  routerParams: any = {};

  // 分类下拉
  classOptions: any = [];
  // 分类ID
  typeId: any = '';
  tableData: any = [];
  subLoading: boolean = false;

  // Modal
  isVisible: boolean = false;
  modelSeachForms: any = {
    name: ''
  }
  modelTableData: any = [];
  modelTableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 10,
    total: 0
  };

  // Model Table 勾选
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = []; // 当前展示页面数据
  setOfCheckedId = new Set<number>(); // 已选ids
  setofCheckedArrs: object[] = []; // 已选项数组

  /**********************************************model表格勾选操作 START**********************************************/ 
  // 勾选设置
  updateCheckedSet(id: number, checked: boolean, item?: any): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      if (this.setofCheckedArrs.length > 0) {
        let isHas = this.setofCheckedArrs.some((tag: any) => { return tag.modelId == id });
        if (!isHas) {
          this.setofCheckedArrs.push({...item, modelId: item.id, sort: '', isChecked: true, id: ''});
        }
      } else {
        this.setofCheckedArrs.push({...item, modelId: item.id, sort: '', isChecked: true, id: ''});
      }
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setofCheckedArrs.findIndex((tag: any) => { return tag.modelId == id });
      this.setofCheckedArrs.splice(delIndex, 1);
    }
  }
  
  // 单选
  onItemChecked(id: number, checked: boolean, item?: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }

  // 全选
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }

  // 当前页面展示数据改变的回调函数
  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  // 全选按钮状态
  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
  /**********************************************model表格勾选操作 END**********************************************/

  constructor(
    private activatedRoute: ActivatedRoute,
    private message: NzMessageService,
    private services: LoveRecycManageService
  ) {
    this.activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    })
  }

  ngOnInit(): void {
    this.getClassOptions();

    if (this.routerParams.type == 1) {
      this.typeId = Number(this.routerParams.typeId);
      this.loadTable(this.routerParams.typeId);
    }
  }

  // 获取分类下拉
  async getClassOptions() {
    try {
      const res: any = await this.services.getClassSelectList({});
      if (res.code == 0) {
        this.classOptions = res.data || [];
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 获取Modal机型列表
  async getTypeTable() {
    try {
      let params: any = {
        name: this.modelSeachForms.name,
        pageNum: this.modelTableForms.page,
        pageSize: this.modelTableForms.pageSize
      }
      this.modelTableForms.tableLoading = true;
      const res: any = await this.services.getTypeModalList(params);
      this.modelTableForms.tableLoading = false;

      if (res.code == 0) {
        const { records, total } = res.data || {};
        this.modelTableData = records || [];
        this.modelTableForms.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.modelTableForms.tableLoading = false;
      this.message.error(error);
    }
  }

  // detail(机型列表)
  async loadTable(typeId: any) {
    try {
      let params: any = {
        pageNum: 1,
        pageSize: 999999,
        typeId: typeId || ''
      }
      const res: any = await this.services.getModelSelectList(params);

      if (res.code == 0) {
        if (res.data?.records.length) {
          res.data.records.forEach((ele: any) => {
            ele.isChecked = ele.status == 1 ? true : false;
          });
        }
        const { records } = res.data || {};
        this.tableData = records || [];
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 分类change
  classChange(classId: any) {
    this.loadTable(classId);
  }

  showModal() {
    this.setOfCheckedId.clear();
    
    this.tableData.forEach((ele: any) => {
      this.setOfCheckedId.add(ele.modelId);
    });
    this.setofCheckedArrs = JSON.parse(JSON.stringify(this.tableData));

    this.getTypeTable();
    this.isVisible = true;
  }

  handleCancel() {
    this.isVisible = false;
  }

  // Modal 查询
  seachData() {
    this.getTypeTable();
  }
  // Modal 重置
  resetData() {
    this.modelSeachForms.name = '';
    this.getTypeTable();
  }
  
  // 关联已选商品
  relationData() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择机型');
      return
    }

    this.tableData = this.setofCheckedArrs || [];
    this.isVisible = false;
  }

  // 删除
  deleteItem(index: number) {
    this.tableData.splice(index, 1);
  }

  // submitData
  async submitData() {
    if (!this.verifData()) {
      return
    }
    let subArray = this.tableData.map((item: any) => {
      return {
        id: item.id ? item.id : '',
        modelId: item.modelId,
        sort: item.sort,
        status: item.isChecked ? 1 : 0
      }
    })

    let params = {
      typeId: this.typeId,
      typeModelList: subArray
    }
    this.subLoading = true;
    const res: any = await this.services.updateModelSelectItem(params);
    this.subLoading = false;

    if (res.code == 0) {
      this.message.success('保存成功');
      history.back();
    } else {
      this.message.error(res.message || '保存失败');
    }
  }

  back() {
    history.back();
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.modelTableForms.page = index;
    this.getTypeTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.modelTableForms.page = 1;
    this.modelTableForms.pageSize = sizeNum;
    this.getTypeTable();
  }

  // 验证
  verifData() {
    if (!this.typeId) {
      this.message.warning('请选择分类');
      return false;
    } else if (!this.tableData.length) {
      this.message.warning('请先添加机型');
      return false;
    } else {
      return true;
    }
  }

  isBtnDisabled() {
    if (this.typeId || String(this.typeId) == '0') {
      return false;
    } else {
      return true;
    }
  }
}
